// @ts-nocheck
import styles from './index.module.less';
import { make } from '../../utils/dom';
import { IconLoader } from '@codexteam/icons';
import { uploadPdf, getPdf } from './api';

class DocParser {
    static get toolbox() {
        return {
            title: 'PDFTextParser',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 256 256"><path fill="#E40046" d="M63.173 0C28.307 0 0 28.305 0 63.17v129.255c0 34.866 28.307 63.172 63.173 63.172h129.254c34.866 0 63.17-28.306 63.17-63.172V63.171C255.597 28.305 227.294 0 192.427 0z"/><path fill="#FFF" d="M108.902 127.708h16.517a5.386 5.386 0 1 1 0 10.77H63.227a5.386 5.386 0 1 1 0-10.77h34.01l.05-.118l32.188-77.417a5.39 5.39 0 0 1 4.867-3.315a5.39 5.39 0 0 1 5.084 3.341l61.943 151.042a5.386 5.386 0 1 1-9.964 4.088L134.408 66.355zm-15.069 36.34q-.029.073-.06.144l-17.108 41.16a5.386 5.386 0 1 1-9.946-4.136l15.449-37.167H51.84a5.386 5.386 0 1 1 0-10.77h62.199a5.386 5.386 0 1 1 0 10.77z"/></svg>`
        };
    }

    static get isReadOnlySupported() {
        return true;
    }

    constructor({ data, api, config, readOnly }) {
        this.data = {
            text: data.text,
        };

        this.api = api;

        this.readOnly = readOnly;

        this.wrapper = undefined;
    }

    render() {
        this.wrapper = make('div', styles['cx-custom-doc']);

        if (this.data && this.data.text) {

        } else {
            // 创建输入框, 按钮
            const controlBox = make('div', styles.controlBox);
            const saveBtn = make('div', styles.saveBtn, { innerText: "上传PDF文件" });
            controlBox.append(saveBtn);
            this.wrapper.append(controlBox);

            // 监听编辑和保存事件
            this.api.listeners.on(saveBtn, 'click', () => {
                const uploadFileFn = (cb: (data: any) => void) => {
                    const fileDom = make('input', '', { type: 'file' });
                    fileDom.style.display = 'none';
                    document.body.append(fileDom);
                    fileDom.click();
                    fileDom.addEventListener('change', async (event: any) => {
                        // 处理文件选择事件
                        const file = event.target.files[0];
                        const data = new FormData();
                        data.set('file', file);
                        cb && cb(data);
                        document.body.removeChild(fileDom);
                    });
                }
                uploadFileFn((data) => {
                    // @ts-ignore
                    saveBtn.innerHTML = `${IconLoader} 正在解析中......`;
                    saveBtn.style.pointerEvents = 'none';
                    uploadPdf(data).then((res: any) => {
                        const { total, fid } = res;

                        // 切换为分页符
                        let curPage = 1;
                        let pageText = `下一页(${curPage}/${total})`;
                        const pageBtn = make('div', styles.pageBtn, { innerText: pageText });

                        getPdfData(curPage, (text) => {
                            this.update(text, curPage >= total);
                        })

                        controlBox.remove();

                        function getPdfData(page: number, cb: (data: any) => void) {
                            getPdf(fid, page).then((res: any) => {
                                const { html } = res;
                                const text = html || '';
                                cb && cb(text);
                            })
                        }

                        this.api.listeners.on(pageBtn, 'click', () => {
                            getPdfData(++curPage, (text) => {
                                this.update(text, curPage >= total);
                                pageText = `下一页(${curPage}/${total})`;
                                pageBtn.innerText = pageText;
                            })
                        })
                        this.wrapper.append(pageBtn);
                    }).catch((err) => {
                        saveBtn.innerHTML = `${IconLoader} 上传失败`;
                    })
                })
            }, false)
        }

        return this.wrapper;
    }

    update(text, isDelDoc) {
        const curIdx = this.api.blocks.getCurrentBlockIndex();
        const curBlock = this.api.blocks.getBlockByIndex(curIdx);
        // 将html转化为文档组件
        const blocks = this.convertHtmlToJson(text);

        // 删除当前块
        if (isDelDoc) {
            this.api.blocks.delete(curIdx);
        }

        if (blocks && blocks.length) {
            blocks.forEach((row, i) => {
                this.api.blocks.insert(row.type, row.data, null, curIdx + i, true);
            })
        }
    }

    convertHtmlToJson(html: string) {
        const blocks = []
        const parser = new DOMParser()
        const doc = parser.parseFromString(html, 'text/html')
        const processNode = (node: Node) => {
            switch (node.nodeName) {
                case 'H1':
                case 'H2':
                case 'H3':
                case 'H4':
                case 'H5':
                case 'H6':
                    blocks.push({
                        type: 'header',
                        data: {
                            text: node.innerHTML,
                            level: parseInt(node.nodeName.charAt(1))
                        }
                    })
                    break
                case 'P':
                    blocks.push({
                        type: 'paragraph',
                        data: {
                            text: node.innerHTML
                        }
                    })
                    break
                case 'UL':
                case 'OL':
                    const items = Array.from(node.childNodes)
                        .filter(child => child.nodeName === 'LI')
                        .map(li => li.innerHTML)
                    blocks.push({
                        type: 'list',
                        data: {
                            style: node.nodeName === 'UL' ? 'unordered' : 'ordered',
                            items: items.map(v => ({ content: v }))
                        }
                    })
                    break
                case 'TABLE':
                    const rows = Array.from(node.querySelectorAll('tr'))
                    const content = rows.map(row =>
                        Array.from(row.querySelectorAll('th, td')).map(cell => cell.textContent || '')
                    )
                    blocks.push(
                        {
                            type: 'table',
                            data: normalizeTableData({
                                withHeadings: rows[0].querySelector('th') !== null,
                                content: content,
                            })
                        }
                    )
                    break
                default:
                    if (node.childNodes) {
                        node.childNodes.forEach(processNode)
                    }
            }
        }

        doc.body.childNodes.forEach(processNode)
        return blocks

    }

    save(blockContent) {
        return this.data
    }

    static get sanitize() {
        return {
            text: true
        };
    }
}

// 定义表格数据类型
interface TableData {
    withHeadings: boolean;
    content: string[][];
}
// 处理表格数据，确保每一行的列数相同
export function normalizeTableData(data: TableData): TableData {
    const maxColumns = Math.max(...data.content.map(row => row.length));

    const normalizedContent = data.content.map(row => {
        const normalizedRow = [...row];
        while (normalizedRow.length < maxColumns) {
            normalizedRow.push('');
        }
        return normalizedRow;
    });

    return {
        withHeadings: data.withHeadings,
        content: normalizedContent,
    };
}

export default DocParser